package com.example.ccmusic

import android.app.Activity
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import kotlinx.coroutines.*

private const val TAG = "MusicAdapter"
class MusicAdapter(
    private val context: Context,
    private val listener: ItemClickListener,
    callback: MusicDiffUtilCallback = MusicDiffUtilCallback()
) :
    ListAdapter<Music, MusicAdapter.MusicViewHolder>(callback) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MusicViewHolder {
//        item无法占满横屏
//        val view = View.inflate(context, R.layout.item_music, null)
        val view = LayoutInflater.from(context).inflate(R.layout.item_music, parent, false)
        return MusicViewHolder(view)
    }

    /**
     * holder 是复用的，不要依赖他的数据
     */
    @OptIn(DelicateCoroutinesApi::class)
    override fun onBindViewHolder(holder: MusicViewHolder, position: Int) {
        val music = getItem(position)
        holder.name.text = music.title
        holder.author.text = music.artist
        GlobalScope.launch(Dispatchers.Main) {
            val img = withContext(Dispatchers.IO) {
                ImageUtils.getBitmapByAlbumId(context, music.albumId)
            }
            holder.icon.setImageBitmap(img)
        }
        holder.itemView.setOnClickListener { listener.onClick(position, getItem(position)) }
    }

    class MusicDiffUtilCallback : DiffUtil.ItemCallback<Music>() {
        override fun areItemsTheSame(oldItem: Music, newItem: Music): Boolean {
            return oldItem.path == newItem.path
        }

        override fun areContentsTheSame(oldItem: Music, newItem: Music): Boolean {
            return oldItem == newItem
        }
    }

    class MusicViewHolder(itemView: View) : ViewHolder(itemView) {
        val icon: ImageView = itemView.findViewById(R.id.music_icon)
        val name: TextView = itemView.findViewById(R.id.music_name)
        val author: TextView = itemView.findViewById(R.id.music_author)
    }

    interface ItemClickListener {
        fun onClick(position: Int, item: Music)
    }

}